// pages/user/merchant/reg/reg.ts

import msg from "../../../../utils/msg";
import { addClub, addClub_record_apply_id, club_apply_detail, get_club_agreement, region_list, uploadPic } from "../../../../utils/request/api";
import { Merchant } from "../../../../utils/request/interface";
import User from "../../../../utils/user";
import { formatTimeYMD } from "../../../../utils/util";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    param: {
      //单位机构基本信息
      company: "", //申请单位名称
      company_type_id: "", //申请单位性质'1407-行政机关','1408-事业单位','1409-社团','1410-企业单位','1411-个体经营'

      club_name: "", //服务机构名称，即前端显示的名称
      club_logo_pic: "", //服务机构logo
      club_area_code: "", //所在地区
      club_address: "", //详细地址
      login_password: "",//密码
      apply_club_gfid: "",
      //单位机构合法性信息
      valid_until_start: "", //营业期限开始时间
      valid_until: "", //营业期限截止时间，不填默认为长期
      certificates: "", //营业执照

      //???
      //apply_club_gfid: "", //关联GF账号id

      //联系人信息
      apply_name: "", //联系人
      contact_phone: "", //联系电话
      email: "", //电子邮箱

      //法人信息
      apply_club_gfnick: "", //法人姓名
      apply_club_phone: "", //法人联系电话
      apply_club_id_card: "", //法人身份证号
      legal_person_id_card_face: "", //法人身份证照片人像面
      legal_person_id_card_back: "", //法人身份证照片国徽面

      //银行及税务信息
      bank_name: "", //开户银行
      bank_branch_name: "", //支行名称
      bank_account: "", //银行帐号
      taxpayer_type: "649", //是否为一般纳税人，648-否，649-是
      taxpayer_pic: "", //一般纳税人证明（照片），taxpayer_type=649时需要传入
    } as Merchant,

    company_type: "请选择",
    company_type_show: false as boolean,//pop
    company_type_columns: ['个体经营', '社团', '企业单位', '事业单位', '行政机关'],

    currentDate: new Date().getTime() as number,//时间选择器用到的时间戳
    pickTime: false as boolean,
    pickTimeName: '' as string,

    //图片
    fileLogo: [] as any, //服务机构logo
    fileCertificates: [] as any,//营业执照
    file_legal_person_id_card_face: [] as any, //法人身份证照片人像面
    file_legal_person_id_card_back: [] as any, //法人身份证照片国徽面
    file_taxpayer_pic: [] as any,//一般纳税人证明（照片）

    showSuccess: false as boolean,

    history: [],//审核历史
    active: 0,
    active_step: 0,
    steps: [
      {
        text: '单位申请',
      },
      {
        text: '平台审核',
      },
      {
        text: '入驻成功',
      },
    ],
    area_code: [],
    area_codes: [],
    pick_area: false,
    min_date: new Date(1980, 1, 1).getTime(),
    area_name: '',
  },
  //注册历史根据时间排序
  _sortByDateDescending(array: any[]) {
    return array.sort((a, b) => {
      const dateA = new Date(a.uDate);
      const dateB = new Date(b.uDate);
      return dateB.getTime() - dateA.getTime();
    });
  },
  back() {
    wx.switchTab({
      url: '/pages/index/index',
    });
  },
  pickArea() {
    this.setData({
      pick_area: true,
    });
  },
  bindInput(e: any) {
    let name = e.currentTarget.dataset.name;
    this.setData({
      ['param.' + name]: e.detail,
    });
  },

  company_type_onChange(e: any) {
    this.setData({
      ['param.company_type_id']: e.detail.index + 1407,
    })
  },
  ClosePopup_company_type() {
    this.setData({
      company_type_show: false,
    })
  },
  onCancel() {
    this.setData({
      company_type_show: false,
    })
  },
  confirmArea(e: any) {
    let area_code: any = this.data.area_code;
    this.setData({
      pick_area: false,
      ['param.club_area_code']: area_code[e.detail.index].code,
      area_name: this.data.area_codes[e.detail.index],
    })
  },
  onConfirm(e: any) {
    this.setData({
      company_type_show: false,
      ['param.company_type_id']: e.detail.index + 1407,
      company_type: this.data.company_type_columns[e.detail.index],
    })
  },
  showPopup_company_type() {
    this.setData({
      company_type_show: true
    });
  },
  closePopup_company_type() {
    this.setData({
      company_type_show: false
    });
  },

  afterReadLogo: async function (event: any) {
    const { file } = event.detail;
    msg.Loading();
    let res = await uploadPic(file.url, 'Filedata')
      .then((res: any) => { return res; });
    if (res.statusCode != 200) {
      msg.show('服务器维护中', '请稍后再试'); return;
    }
    let data = res.data;
    if (typeof data == 'string') data = JSON.parse(data);
    let fileName = data.savename;
    let fileList = [];
    fileList.push(file);
    this.setData({
      fileLogo: fileList,
      ['param.club_logo_pic']: fileName,
    });
    msg.hideLoading();
  },
  Del_logo: function () {
    this.setData({
      fileLogo: [],
      ['param.club_logo_pic']: '',
    });
  },
  history() {
    this.onShow();
    this.setData({
      active: 1,
      showSuccess: false,
    });
  },
  afterReadCertificates: async function (event: any) {
    const { file } = event.detail;
    msg.Loading();
    let res = await uploadPic(file.url, 'Filedata')
      .then((res: any) => { return res; });
    if (res.statusCode != 200) {
      msg.show('服务器维护中', '请稍后再试'); return;
    }
    let data = res.data;
    if (typeof data == 'string') data = JSON.parse(data);
    let fileName = data.savename;
    let fileList = [];
    fileList.push(file);
    this.setData({
      fileCertificates: fileList,
      ['param.certificates']: fileName,
    });
    msg.hideLoading();
  },
  Del_certificates: function () {
    this.setData({
      fileCertificates: [],
      ['param.certificates']: '',
    });
  },

  afterRead_id_card_face: async function (event: any) {
    const { file } = event.detail;
    msg.Loading();
    let res = await uploadPic(file.url, 'Filedata')
      .then((res: any) => { return res; });
    if (res.statusCode != 200) {
      msg.show('服务器维护中', '请稍后再试'); return;
    }
    let data = res.data;
    if (typeof data == 'string') data = JSON.parse(data);
    let fileName = data.savename;
    let fileList = [];
    fileList.push(file);
    this.setData({
      file_legal_person_id_card_face: fileList,
      ['param.legal_person_id_card_face']: fileName,
    });
    msg.hideLoading();
  },
  Del_id_card_face: function () {
    this.setData({
      file_legal_person_id_card_face: [],
      ['param.legal_person_id_card_face']: '',
    });
  },
  afterRead_id_card_back: async function (event: any) {
    const { file } = event.detail;
    msg.Loading();
    let res = await uploadPic(file.url, 'Filedata')
      .then((res: any) => { return res; });
    if (res.statusCode != 200) {
      msg.show('服务器维护中', '请稍后再试'); return;
    }
    let data = res.data;
    if (typeof data == 'string') data = JSON.parse(data);
    let fileName = data.savename;
    let fileList = [];
    fileList.push(file);
    this.setData({
      file_legal_person_id_card_back: fileList,
      ['param.legal_person_id_card_back']: fileName,
    });
    msg.hideLoading();
  },
  Del_id_card_back: function () {
    this.setData({
      file_legal_person_id_card_back: [],
      ['param.legal_person_id_card_back']: '',
    });
  },
  afterRead_tax_pic: async function (event: any) {
    const { file } = event.detail;
    msg.Loading();
    let res = await uploadPic(file.url, 'Filedata')
      .then((res: any) => { return res; });
    if (res.statusCode != 200) {
      msg.show('服务器维护中', '请稍后再试'); return;
    }
    let data = res.data;
    if (typeof data == 'string') data = JSON.parse(data);
    let fileName = data.savename;
    let fileList = [];
    fileList.push(file);
    this.setData({
      file_taxpayer_pic: fileList,
      ['param.taxpayer_pic']: fileName,
    });
    msg.hideLoading();
  },
  Del_tax_pic: function () {
    this.setData({
      file_taxpayer_pic: [],
      ['param.taxpayer_pic']: '',
    });
  },

  onChange2(e: any) {
    this.setData({
      ['param.taxpayer_type']: e.detail,
    });
  },

  onInput(event: any) {
    this.setData({
      currentDate: event.detail,
    });
  },

  pickTime(e: any) {
    let name = e.currentTarget.dataset.name;
    this.setData({
      pickTime: true,
      pickTimeName: name,
    });
  },
  confirmTime(e: any) {
    let format_time = formatTimeYMD(new Date(e.detail));
    this.setData({
      ['param.' + this.data.pickTimeName]: format_time,
    });
    this.onClose();
  },
  onClose() {
    this.setData({
      pickTime: false,
      pick_area: false,
    })
  },

  submit: async function () {
    let user = new User;
    if (user.apply_id) {
      await msg.confirm('您已经提交过商户申请了,是否确认再次提交', '');
    }
    if (!this.checkValid()) return;

    msg.Loading('提交中');
    console.log('this.data.param)=', this.data.param);
    let res: any = await addClub(this.data.param);
    msg.hideLoading();
    console.log('submit_res=', res);
    if (res.data.error == '0') {
      //记录apply_id
      addClub_record_apply_id({ openid: user.openid, apply_id: res.data.apply_id })
      this.setData({
        showSuccess: true,
      });
      this.onShow();
    }
    else {
      msg.show('提交失败', '请检查网络设置');
    }
  },
  checkValid() {
    let param: any = this.data.param;
    let user = new User;
    param['apply_club_gfid'] = user.GF_ID;
    for (let key in param) {
      let temp = param[key];
      if (key == 'taxpayer_pic' && param['taxpayer_type'] != 649) {
        continue;
      }
      if (!temp && (key != 'game_small_pic' && key != "game_big_pic")) {
        msg.show('请输入完整表单'); return false;
      }
    }
    //if(!this.data.fileSmallPic.length){ msg.show('请输入完整表单');return false;}
    //if(!this.data.fileBigPic.length){ msg.show('请输入完整表单');return false;}
    return true;
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad:async function() {
    msg.Loading();
    await region_list({})
      .then((res: any) => {
        let area_codes: any = [];
        res.data.datas.forEach((element: any) => {
          area_codes.push(element.region_name_c);
        });
        this.setData({
          area_code: res.data.datas,
          area_codes: area_codes,
        });
        msg.hideLoading();
      });
    let res = await get_club_agreement();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  async onShow() {
    //注册历史
    let user = new User;
    if (user.apply_id) {
      let apply_id = user.apply_id.split(',');
      let history: any = [];
      for (let i = 0; i < apply_id.length; i++) {
        //if(apply_id[i])
        await club_apply_detail({ visit_gfid: user.GF_ID, apply_id: apply_id[i] })
          .then((res: any) => {
            if (res.data.error != 0) return;
            let temp = res.data.datas;
            if (temp.state_name == '待认证') temp['active'] = 0;
            else if (temp.state_name == '待审核') temp['active'] = 1;
            else temp['active'] = 4;
            history.push(temp);
          });
      }
      history = this._sortByDateDescending(history);
      this.setData({ history });
    }

  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})